﻿using EventBus;
using LiteStep.Arbitrage;
using LiteStep.Events;
using LiteStep.Events.Handlers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteStep.Console
{
    public class ArbitrageWriter : IArbitrageCalculationUpdatedEventHandler
    {
        IDictionary<string, ArbitrageCalculation> Map { get; set; }

        public ArbitrageWriter(IEventBus eventBus)
		{
            Map = new Dictionary<string, ArbitrageCalculation>();
			eventBus.AddHandler(ArbitrageCalculationUpdatedEvent.TYPE, this);
		}

        public void OnArbitrageCalculationUpdatedEvent(ArbitrageCalculationUpdatedEvent e)
        {
            lock (this)
            {
                if (e == null || e.Calculation == null || string.IsNullOrEmpty(e.Calculation.Key)) return;

                Map[e.Calculation.Key] = e.Calculation;

                var orderedCalculations = Map.Values.OrderByDescending(c => c.PercentageChange).ToList();

                var sb = new StringBuilder();
                for (var i = 0; i < Math.Min(orderedCalculations.Count, 60); i++)
                {
                    sb.AppendLine(string.Format("{0} | Percentage Change: {1}%\tValue Change: {2}\tUSD Change: ${3}", orderedCalculations[i].Key, orderedCalculations[i].PercentageChange * 100M, orderedCalculations[i].ValueChange, orderedCalculations[i].UsdChange));
                }

                System.Console.Clear();
                System.Console.WriteLine(sb);
            }
        }
    }
}
